'''
Created on Jul 7, 2010

@author: Behrooz Nobakht
'''
from amscms.ams.models import AdView, AdStats, Ad
import re
from amscms.core.utils.request import meta_netloc, meta_remote_ip

class AdViewMiddleware:
    
    def process_request(self, request):
        if re.search("ads/view/\\d+", request.path) is None or re.search("report/", request.path) is not None:
            return None
        result = re.search("(?<=/view/)\\d+", request.path)
        ad_id = result.group(0)
        if ad_id is None:
            return None
        if request.user is None:
            return None
        the_user = None if request.user.is_anonymous() else request.user
        if the_user is not None:
            """
            we do not count the times that the owner user is viewing
            her own ads. Also, notice that if the user is anonymously viewing
            her owns ads, we're counting them but as anonymous visitors.
            """
            if Ad.objects.owns(ad_id, the_user):
                return None
        referer = meta_netloc(request)
        viewer_ip = meta_remote_ip(request)
        AdView.objects.add_adview(ad_id, the_user, referer, viewer_ip)
        AdStats.objects.update_views_stats(ad_id)
        return None
        
        
 
